package com.foxmail.aroundme.boring.manager;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.foxmail.aroundme.boring.BuildConfig;
import com.foxmail.aroundme.boring.R;
import com.foxmail.aroundme.boring.app.App;
import com.foxmail.aroundme.boring.bean.channel.NewsChannelBean;
import com.foxmail.aroundme.boring.utils.Config;
import com.foxmail.aroundme.boring.utils.m_enum.ChannelType;
import com.foxmail.aroundme.boring.utils.util.ListUtils;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;


public class ChannelManager {
    private static final String HOT = "10001";
    private static ChannelManager sManager;

    private List<NewsChannelBean> channelDatas = new ArrayList<NewsChannelBean>();
    private List<NewsChannelBean> channelNews = new CopyOnWriteArrayList<NewsChannelBean>();

    private ChannelManager() {
    }

    public static ChannelManager getInstance() {
        if (sManager == null) {
            synchronized (ChannelManager.class) {
                if (sManager == null) {
                    sManager = new ChannelManager();
                }
            }
        }
        return sManager;
    }


    /**
     * 初始化频道数据
     *
     * @param beans
     */
    public void initChannel(final List<NewsChannelBean> beans, final int version) {

        if (beans == null) {
            return;
        }

        if (ListUtils.isEmpty(beans)) {
            return;
        }

        final List<String> newIds = new ArrayList<String>();
        final List<String> oldIds = new ArrayList<String>();

        //初始化下发数据
        for (NewsChannelBean bean : beans) {
            bean.currentIndex = bean.defaultIndex;
            newIds.add(bean.id);
        }

        channelNews.clear();
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {

                //取出原来数据库中数据
                List<NewsChannelBean> beanList = getChannelList();
                //保存用户修改数据
                List<NewsChannelBean> userChanges = new ArrayList<NewsChannelBean>();

                //标示是否有新增频道数据
                boolean isNewsChannel = false;

                if (!ListUtils.isEmpty(beanList)) {

                    int oldSize = beanList.size();
                    for (int i = 0; i < oldSize; i++) {
                        NewsChannelBean bean = beanList.get(i);
                        //保存旧的数据ID
                        oldIds.add(bean.id);

                        //保存用户修改的频道数据
                        if (bean.userChange == 1) {
                            userChanges.add(bean);
                        }
                    }
                    //删除newIds中有的频道数据
                    newIds.removeAll(oldIds);

                    isNewsChannel = !newIds.isEmpty();
                }

                //标记新频道
                int newIdSize = newIds.size();
                int pullSize = beans.size();
                for (int i = 0; i < newIdSize; i++) {

                    String b1 = newIds.get(i);

                    for (int j = 0; j < pullSize; j++) {
                        NewsChannelBean newChannel = beans.get(j);

                        if (TextUtils.equals(b1, newChannel.id)) {
                            newChannel.tag = Config.NEW;
                            channelNews.add(newChannel);
                        }
                    }
                }


                //用户修改数据调整
                int userChangeSize = userChanges.size();
                for (int i = 0; i < userChangeSize; i++) {
                    NewsChannelBean bean = userChanges.get(i);

                    for (int j = 0; j < pullSize; j++) {
                        NewsChannelBean newChannel = beans.get(j);
                        if (TextUtils.equals(bean.id, newChannel.id)) {
                            newChannel.currentIndex = bean.currentIndex;
                            newChannel.userChange = 1;
                        }
                    }
                }
                if (BuildConfig.DEBUG) {
                    KLog.i("排序前=" + beans);
                }

                //将频道数据进行排序
                Collections.sort(beans, new Comparator<NewsChannelBean>() {
                    @Override
                    public int compare(NewsChannelBean lhs, NewsChannelBean rhs) {
                        if (lhs.currentIndex > rhs.currentIndex) {
                            return 1;
                        } else if (lhs.currentIndex == rhs.currentIndex) {
                            if (rhs.fix == Config.FIX) {
                                return 1;
                            } else if (rhs.userChange == 1) {
                                return 1;
                            } else {
                                return -1;
                            }
                        }
                        return 0;
                    }
                });
                if (BuildConfig.DEBUG) {
                    KLog.i("排序后=" + beans);
                }

                //初始化下发数据
                for (int i = 0; i < beans.size(); i++) {
                    NewsChannelBean bean = beans.get(i);
                    bean.currentIndex = i;
                }

                if (BuildConfig.DEBUG) {
                    KLog.i("位置后=" + beans);
                }

                channelDatas.clear();
                channelDatas.addAll(beans);
                //int count = ProviderManger.getInstance().getWorkWriter(App.getContext()).deleteData(DatabaseConstants.TBL_G, null, null);
                if (BuildConfig.DEBUG) {
                    //KLog.i("频道数据删除成功=" + count);
                }

                //ProviderManger.getInstance().getWorkWriter(BaApp.getContext()).saveLists(DatabaseConstants.TBL_G, beans);

                //NormalPrefsUtils.with().writeInt(SpreConfig.CURRENT_CHANNEL_VERSION, version);
                if (BuildConfig.DEBUG) {
                    KLog.i("请求频道数据完成==");
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).subscribe(new Subscriber<Object>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(Object o) {
            }
        });
    }

    /**
     * 修改频道后保存数据库
     *
     * @param beans
     */

    public void changeChannel(final List<NewsChannelBean> beans) {

        final List<NewsChannelBean> newsChannelBeanList = new ArrayList<NewsChannelBean>();
        newsChannelBeanList.addAll(beans);
        channelDatas.clear();
        channelDatas.addAll(newsChannelBeanList);

        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                //int count = ProviderManger.getInstance().getWorkWriter(BaApp.getContext()).deleteData(DatabaseConstants.TBL_G, null, null);
                if (BuildConfig.DEBUG) {
                    //KLog.i("修改频道数据删除成功=" + count);
                }
                //ProviderManger.getInstance().getWorkWriter(BaApp.getContext()).saveLists(DatabaseConstants.TBL_G, newsChannelBeanList);

                if (BuildConfig.DEBUG) {
                    KLog.i("修改频道数据完成");
                }
            }
        }).subscribeOn(Schedulers.io()).subscribe();
    }

    public List<NewsChannelBean> getChannelList() {

        List<NewsChannelBean> teamp = new ArrayList<NewsChannelBean>();
        teamp.addAll(channelDatas);

        if (!teamp.isEmpty()) {
            return teamp;
        }

        //String sql = new NewsSql(NewsSql.QUERY, DatabaseConstants.TBL_G).orderBy().asc(DatabaseConstants.C).build();
        //teamp = ProviderManger.getInstance().getWorkReader(BaApp.getContext()).getData(sql, NewsChannelBean.class);
        if (teamp == null) {
            if (BuildConfig.DEBUG) {
                KLog.i("下发频道数据为空");
            }
            teamp = getDefaultChannel();
            return teamp;
        }

        int size = teamp.size();
        if (size == 0) {

            teamp = getDefaultChannel();
            return teamp;
        }

        for (int i = 0; i < size; i++) {
            NewsChannelBean bean = teamp.get(i);
            if (HOT.equals(bean.id)) {
                bean.fix = 1;
                break;
            }
        }

        return teamp;
    }

    @NonNull
    private List<NewsChannelBean> getDefaultChannel() {
        List<NewsChannelBean> tables = new ArrayList<NewsChannelBean>();
        String channel[] = App.getContext().getResources().getStringArray(R.array.channel);
        String channelId[] = App.getContext().getResources().getStringArray(R.array.channel_id);
        for (int i = 0; i < channel.length; i++) {
            NewsChannelBean newsChannal = new NewsChannelBean();
            newsChannal.id = channelId[i];
            newsChannal.name = channel[i];
            newsChannal.currentIndex = i;
            newsChannal.defaultIndex = i;
            newsChannal.userChange = 0;
            newsChannal.fix = newsChannal.id.equals(HOT) ? 1 : 0;
            tables.add(newsChannal);
        }
        return tables;
    }

    public void getChannelNews(List<NewsChannelBean> channels) {
        channels.addAll(channelNews);
        channelNews.clear();
    }


    /**
     *
     * 因为chanelId不同而使用的接口一致，传参不同，所以再此区分
     * @param channelId
     * @return
     */
    public String disPatchChannelType(@ChannelType.Channel String channelId) {
        //默认为头条
        String type = "top";
        switch (channelId) {
            case ChannelType.top:
                type ="top";
                break;
            case ChannelType.shehui:
                type ="shehui";
                break;
            case ChannelType.guonei:
                type ="guonei";
                break;
            case ChannelType.guoji:
                type ="guoji";
                break;
            case ChannelType.yule:
                type ="yule";
                break;
            case ChannelType.tiyu:
                type ="tiyu";
                break;
            case ChannelType.junshi:
                type ="junshi";
                break;
            case ChannelType.keji:
                type ="keji";
                break;
            case ChannelType.caijing:
                type ="caijing";
                break;
            case ChannelType.shishang:
                type ="shishang";
                break;
        }

        return type;
    }

}
